package com.gears_software.sxdc.dccx.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.gears_software.sxdc.dccx.R;
import com.gears_software.sxdc.dccx.application.DCCXApplication;
import com.gears_software.sxdc.dccx.data.finder.IBaseFinder;
import com.gears_software.sxdc.dccx.data.finder.IMemberFinder;
import com.gears_software.sxdc.dccx.data.finder.RequestUrl;
import com.gears_software.sxdc.dccx.data.finder.util.GearsErrorHandler;
import com.gears_software.sxdc.dccx.data.model.ResultModel;
import com.gears_software.sxdc.dccx.data.model.request.RNameAuthenticationModel;
import com.gears_software.sxdc.dccx.ui.util.MaterialDialogProgress;
import com.gears_software.sxdc.dccx.ui.util.PictureUtils;
import com.gears_software.sxdc.dccx.ui.util.popu.PhotoPopup;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.sdsmdg.tastytoast.TastyToast;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import org.androidannotations.rest.spring.annotations.RestService;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import qiu.niorgai.StatusBarCompat;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;


/**
 * Created by chezhenzhen on 2017/7/26.
 */

@EActivity(R.layout.activity_shiming)
public class ShiMingActivity extends AppCompatActivity implements PhotoPopup.PhotocallBack {
    @App
    DCCXApplication app;
    @ViewById
    TextView actionbar_title;
    @ViewById
    TextView back_icon;
    @ViewById
    TextView right_icon;
    @ViewById
    TextView txt_addicon;
    @ViewById
    TextView txt_addicon1;
    @ViewById
    TextView txt_addicon2;
    @ViewById
    EditText et_realName;
    @ViewById
    Button btn_submit;
    @ViewById
    SimpleDraweeView img_card1;
    @ViewById
    SimpleDraweeView img_card2;
    @ViewById
    SimpleDraweeView img_card3;
    @ViewById
    LinearLayout ly_card1;
    @ViewById
    LinearLayout ly_card2;
    @ViewById
    LinearLayout ly_card3;
    @RestService
    IMemberFinder iMemberFinder;
    @RestService
    IBaseFinder baseFinder;
    @Bean
    GearsErrorHandler errorHandler;

    MaterialDialogProgress progress;
    private String mPublicPhotoPath;
    private Uri uri;
    private static final int REQ_GALLERY = 333;  //拍照
    private static final int REQUEST_CODE_PICK_IMAGE = 222;   //相册

    Context context;

    RNameAuthenticationModel model;
    String flag = "";


    @AfterViews
    void created() {
        context = this;
        initIconFont();
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.colorActionbar));

        progress = new MaterialDialogProgress(this);
        model = new RNameAuthenticationModel();
        iMemberFinder.setRestErrorHandler(errorHandler);
        baseFinder.setRestErrorHandler(errorHandler);

    }

    void initIconFont() {
        actionbar_title.setText("实名认证");
        back_icon.setVisibility(View.VISIBLE);
        back_icon.setText(R.string.back_icon);
        back_icon.setTypeface(app.iconfont);
        right_icon.setVisibility(View.GONE);
        txt_addicon.setTypeface(app.iconfont);
        txt_addicon1.setTypeface(app.iconfont);
        txt_addicon2.setTypeface(app.iconfont);
    }

    @Click
    void ly_card1() {
        flag = "card1";
        showPhotoPopup();
    }

    @Click
    void ly_card2() {
        flag = "card2";
        showPhotoPopup();
    }

    @Click
    void ly_card3() {
        flag = "card3";
        showPhotoPopup();
    }

    void showPhotoPopup() {
        PhotoPopup popup = new PhotoPopup(this);
        popup.setPhotoClick(this);
        popup.showPopupWindow();
    }

    @Override
    public void photoClick(int photoTag) {
        //拍照
        if (photoTag == 0) {
            AndPermission.with(this)
                    .requestCode(100)
                    .permission(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE)
                    .callback(listener)
                    .rationale(new RationaleListener() {
                        @Override
                        public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                            // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                            AndPermission.rationaleDialog(context, rationale).
                                    show();
                        }
                    })
                    .start();
        } else if (photoTag == 1) { //从手机相册选择
            AndPermission.with(this)
                    .requestCode(200)
                    .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                    .callback(listener)
                    .rationale(new RationaleListener() {
                        @Override
                        public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                            // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                            AndPermission.rationaleDialog(context, rationale).
                                    show();
                        }
                    })
                    .start();

        }
    }

    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantedPermissions) {
            // 权限申请成功回调。
            if (requestCode == 100) {
                //打开相机
                openCreame();
            } else if (requestCode == 200) {
                //打开相册
                openPhoto();
            }
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            // 权限申请失败回调。
            if (requestCode == 100) {
                TastyToast.makeText(context, "获取系统相机权限失败", TastyToast.LENGTH_SHORT, TastyToast.DEFAULT);

            } else if (requestCode == 200) {
                TastyToast.makeText(context, "获取系统上的照片、媒体内容和文件权限失败", TastyToast.LENGTH_SHORT, TastyToast.DEFAULT);

            }
        }
    };

    private void openCreame() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File photoFile = null;
        try {
            photoFile = PictureUtils.createPublicImageFile();
            mPublicPhotoPath = photoFile.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //设置Action为拍照
        if (photoFile != null) {
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            //这里加入flag
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri photoURI = FileProvider.getUriForFile(this, "com.gears_software.sxdc.dccx.provider", photoFile);
            // czzltp 解决适配Android7.0调用相机报权限问题
            List<ResolveInfo> resInfoList = getPackageManager()
                    .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo resolveInfo : resInfoList) {
                String packageName = resolveInfo.activityInfo.packageName;
                grantUriPermission(packageName, photoURI, Intent.FLAG_GRANT_READ_URI_PERMISSION
                        | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(intent, REQ_GALLERY);
        }
    }

    private void openPhoto() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");//相片类型
        startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String path = "";
        switch (requestCode) {
            //拍照
            case REQ_GALLERY:
                if (resultCode != RESULT_OK) return;
                uri = Uri.parse(mPublicPhotoPath);
                path = uri.getPath();
                PictureUtils.galleryAddPic(mPublicPhotoPath, this);
                break;
            //获取相册的图片
            case REQUEST_CODE_PICK_IMAGE:
                if (data == null) return;
                uri = data.getData();
                int sdkVersion = Integer.valueOf(Build.VERSION.SDK);
                if (sdkVersion >= 19) {
                    path = this.uri.getPath();
                    path = PictureUtils.getPath_above19(this, this.uri);
                } else {
                    path = PictureUtils.getFilePath_below19(this, this.uri);
                }
                break;
        }
//        img_avatar.setImageBitmap(PictureUtils.getSmallBitmap(path, img_avatar.getWidth(), img_avatar.getHeight()));
        File file = new File(path);
        //图片压缩
        Luban.with(context).load(file).setCompressListener(new OnCompressListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(File file) {
                progress.show("正在上传...");
                getToken(file);
            }

            @Override
            public void onError(Throwable e) {

            }
        }).launch();
    }

    @Background
    void getToken(File file) {
        ResultModel<String> result = baseFinder.getToken();
        showTokenResult(file, result);
    }

    @UiThread
    void showTokenResult(File file, ResultModel<String> result) {
        if (result != null) {
            if (result.getErrno().equals("0")) {
                if (result.getData() != null && !result.getData().equals("")) {
                    String token = result.getData();
                    uploadAvatar(file, token);
                }
            }
        }
    }

    //七牛上专图片
    void uploadAvatar(File file, String token) {
        String key = UUID.randomUUID().toString();
        app.uploadManager.put(file, key, token, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject response) {
                //res包含hash、key等信息，具体字段取决于上传策略的设置
                if (info.isOK()) {
                    String avatarUrl = RequestUrl.QiNiuDomain + key;
                    Uri uri = Uri.parse(avatarUrl + RequestUrl.card);
                    if (!flag.equals("")) {
                        if (flag.equals("card1")) {
                            model.setIdphoto1(avatarUrl);
                            img_card1.setVisibility(View.VISIBLE);
                            img_card1.setImageURI(uri);
                            ly_card1.setVisibility(View.GONE);
                        } else if (flag.equals("card2")) {
                            model.setIdphoto2(avatarUrl);
                            img_card2.setVisibility(View.VISIBLE);
                            img_card2.setImageURI(uri);
                            ly_card2.setVisibility(View.GONE);
                        } else if (flag.equals("card3")) {
                            model.setHoldid(avatarUrl);
                            img_card3.setVisibility(View.VISIBLE);
                            img_card3.setImageURI(uri);
                            ly_card3.setVisibility(View.GONE);
                        }
                    }

                } else {
                    TastyToast.makeText(context, "上传失败", app.SHORT, app.ERROR);
                }
                progress.dismiss();
            }
        }, null);
    }

    @Click
    void btn_submit() {
        if (et_realName.getText().toString().equals("")) {
            TastyToast.makeText(this, "请填写真实姓名", app.SHORT, app.WARNING);
        } else if (model.getHoldid() == null || model.getHoldid().equals("")) {
            TastyToast.makeText(this, "请上传身份证正面照片", app.SHORT, app.WARNING);
        } else if (model.getIdphoto1() == null || model.getIdphoto1().equals("")) {
            TastyToast.makeText(this, "请上传身份证反面照片", app.SHORT, app.WARNING);
        } else if (model.getIdphoto2() == null || model.getIdphoto2().equals("")) {
            TastyToast.makeText(this, "请上传手持身份证照片", app.SHORT, app.WARNING);
        } else {
            model.setFname(et_realName.getText().toString());
            nameAuthentication(model);
        }
    }

    @Background
    void nameAuthentication(RNameAuthenticationModel modle) {
        ResultModel<String> result = iMemberFinder.nameAuthentication(modle);
        showResult(result);
    }

    @UiThread
    void showResult(ResultModel<String> result) {
        if (result != null) {
            if (result.getErrno().equals("0")) {
                TastyToast.makeText(this, "实名认证信息提交成功", app.SHORT, app.SUCCESS);
                finish();
                Intent intent = new Intent(this,SMRZTGActivity_.class);
                startActivity(intent);
            } else {
                TastyToast.makeText(this, result.getErrmsg(), app.SHORT, app.ERROR);
            }
        }
    }

    @Click
    void back_icon() {
        this.finish();
    }


}
